package com.xnx3.wangmarket.plugin.serviceLog;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.springframework.stereotype.Component;

import com.xnx3.DateUtil;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.ElasticSearchUtil;
import com.xnx3.j2ee.util.actionLog.ElasticSearchMode;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.pluginManage.interfaces.MessageInterface;
import com.xnx3.kefu.core.util.SocketUtil;
import com.xnx3.kefu.core.util.UserUtil;
import com.xnx3.kefu.core.vo.MessageReceiveVO;
import com.xnx3.kefu.core.vo.bean.MessageTypeEnum;
import io.netty.channel.Channel;
import net.sf.json.JSON;
import net.sf.json.JSONObject;

/**
 * 消息接口的实现
 * @author 管雷鸣
 *
 */
public class MessageInterfaceImpl implements MessageInterface{
	public static final String INDEX = "zuoxi_service_time";
	
	static{
		ElasticSearchUtil.projectStartCheckCreateIndex(INDEX);
	}
	
	@Override
	public void offlineMessage(Channel channel, MessageReceiveVO message) {
	}

	@Override
	public void online(Channel channel) {
	}

	@Override
	public void offline(Channel channel) {
		//一个人离线，基本属于访客咨询完成触发。也有可能是客服网络中断导致离线
		
		//离线，那么坐席结束服务
		over_service(channel);
	}

	@Override
	public void autoReply(Channel channel, String otherChatId) {
		//自动回复，也就是建立对话窗口时就会触发
		
		//取出当前socket连接的用户信息
		ChatUserBean chatUserBean = SocketUtil.getUser(channel);
		if(chatUserBean == null){
			ConsoleUtil.log("异常--chatUserBean is null");
			return;
		}
		
		//标记当前客服开始服务，写日志
		Map<String, Object> params = new HashMap<String, Object>();
		
		ChatUserBean zuoxiChatUserbean = null;	//客服坐席的chatUser
		if(chatUserBean.getType().equals("user")){
			//是普通用户（坐席）
			zuoxiChatUserbean = chatUserBean;
			
			params.put("otherChatId", otherChatId);	//另一方
		}else{
			//是游客，那另一方即使坐席客服
			zuoxiChatUserbean = UserUtil.getUser(otherChatId);
			if(zuoxiChatUserbean == null){
				ConsoleUtil.log("异常-- otherchatid chatUserBean is null, otherChatid:"+otherChatId);
				return;
			}
			
			params.put("otherChatId", chatUserBean.getChatid());	//另一方，也就是游客的chatid
		}
		
		params.put("zuoxiChatId", zuoxiChatUserbean.getChatid());
		params.put("type", "START_SERVICE");	//标记为开始服务
		params.put("time", DateUtil.timeForUnix10());
		//记录开始日志
//		ActionLogUtil.logExtend(params);
//		ElasticSearchMode.es.put(params, INDEX);
//		ConsoleUtil.debug(JSONObject.fromObject(params).toString());
	}

	@Override
	public boolean messageReceivedChat(Channel channel, MessageReceiveVO msg) {
		//确认type 是 CLOSE_SERVICE
		if(msg.getType().equalsIgnoreCase(MessageTypeEnum.CLOSE_SERVICE.name)){
			return false;
		}
		
		return true;
	}
	
	public void over_service(Channel channel) {
		// TODO Auto-generated method stub
	}
	
}
